package com.muh.controller;

import com.muh.entity.User;
import com.muh.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

@RestController
@RequestMapping("user")
public class UserController {

    @Autowired
    private UserRepository userRepository;
    @PostMapping("addDocuments")
    public Object addDocuments(@RequestBody List<User> users) {
        return userRepository.saveAll(users);
    }

    @GetMapping("findById")
    public User findById(Long id) {
        return userRepository.findById(id).get();
    }

    @GetMapping("findAll")
    public List<User> findAll() {
        Iterator<User> iterator = userRepository.findAll().iterator();
        List<User> employeeList = new ArrayList<User>();
        iterator.forEachRemaining(employeeList::add);
        return employeeList;
    }

    @GetMapping("findEmployeesByDescription")
    public List<User> findEmployeesByAddress(@RequestParam("description") String description) {
        return userRepository.findUsersByDescription(description);
    }

    @GetMapping("findAllPage")
    public Page<User> findAllPage(@RequestParam(defaultValue = "0") int pageNumber,
                                      @RequestParam(defaultValue = "10") int pageSize) {
        Pageable pageable = PageRequest.of(pageNumber, pageSize, Sort.Direction.ASC,"age");
        Page<User> all = userRepository.findAll(pageable);
        return all;
    }

    @GetMapping("findPageByDescription")
    public Page<User> findPageByAddress(@RequestParam String description,
                                            @RequestParam(defaultValue = "0") int pageNumber,
                                            @RequestParam(defaultValue = "10") int pageSize) {
        Pageable pageable = PageRequest.of(pageNumber, pageSize, Sort.Direction.DESC,"age");
        Page<User> usersByDescription = userRepository.findUsersByDescription(description, pageable);
        return usersByDescription;
    }

}